/**
 * @description 工具栏：查询组件
 * @author chenyan
 */

import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { CheckOutlined } from '@ant-design/icons';
import { Form, Icon as LegacyIcon } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Spin, Row, Col, Tooltip, Button, Popover, message } from 'antd';
import styleCommom from '../../../../css/colors.js';
import upPng from '../../../../assets/commom/up_arrow.png';
import downPng from '../../../../assets/commom/down_arrow.png';
import styles from './index.less';
import { isZiGuanEvir } from '../../../../utils/commonFunc';
@Form.create()
class HeaderC extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      dataObj: {}, //信息对象
      bondGroupList: [], //个券关注列
      mainGroupList: [], //主体关注列
      newBondList: [], //选择后个券关注列
      newMainList: [], //选择后主体关注列
      visibleBond: false, //个券关注列表弹窗
      visibleMain: false, //主体关注列表弹窗
      isLoading: false,
      starBondFilled: false, //个券关注icon true-实心
      starMainFilled: false, //主体关注icon
    };
  }

  componentDidMount() {
    const { bondID, exchangeCode, tradingCode } = this.props;
    if (bondID) this.queryHeaderData(bondID, exchangeCode, tradingCode);
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (this.props.bondID !== nextProps.bondID) {
      if (nextProps.bondID) {
        this.queryHeaderData(nextProps.bondID, nextProps.exchangeCode, nextProps.tradingCode);
      } else {
        this.setState({
          dataObj: {},
        });
      }
    }
  }

  //获取头部个券信息
  queryHeaderData = (secucode, exchangeCode, tradingCode) => {
    this.props.dispatch({
      type: 'bondDeviationDetailM/queryBasicInfoSnapshot',
      payload: {
        secucode,
        exchangeCode: exchangeCode,
        tradingCode: tradingCode,
      },
      callback: (data) => {
        if (data) {
          this.setState(
            {
              dataObj: data,
            },
            () => {
              this.getAttentionTable();
            },
          );
        } else {
          this.setState({
            dataObj: {},
          });
        }
      },
    });
  };

  //获取关注列表
  getAttentionTable = () => {
    const { dataObj } = this.state;
    const { exchangeCode } = this.props;
    this.props.dispatch({
      type: 'bondDeviationDetailM/getSecurityGroups',
      payload: {
        tradingCode: dataObj.TRADINGCODE_NOSUFFIX,
        exchangeCode: dataObj.EXCHANGECODE,
      },
      callback: (res) => {
        const start = res.list.filter((item) => {
          return item.isAttention;
        });
        this.setState({
          bondGroupList: res.list,
          newBondList: res.list,
          starBondFilled: start.length > 0 ? true : false,
        });
      },
    });
    if (exchangeCode != '390') {
      this.props.dispatch({
        type: 'bondDeviationDetailM/getCompanyGroups',
        payload: {
          comcode: dataObj.COMCODE,
        },
        callback: (res) => {
          const start = res.list.filter((item) => {
            return item.isAttention;
          });
          this.setState({
            mainGroupList: res.list,
            newMainList: res.list,
            starMainFilled: start.length > 0 ? true : false,
          });
        },
      });
    }
  };

  //点击关注按钮事件
  attentionBtn = (type) => {
    const { bondGroupList, mainGroupList, visibleBond, visibleMain } = this.state;
    if (type == 'bond') {
      if (bondGroupList.length == 0) {
        //无关注组时
        message.warning('请先添加个券的关注分组');
      } else {
        this.setState({
          visibleBond: !visibleBond,
          visibleMain: false,
        });
      }
    } else {
      if (mainGroupList.length == 0) {
        message.warning('请先添加主体的关注分组');
      } else {
        this.setState({
          visibleMain: !visibleMain,
          visibleBond: false,
        });
      }
    }
  };

  //关注列表点击事件
  listClick = (e, id, type) => {
    if (type == 'bond') {
      const list = JSON.parse(JSON.stringify(this.state.newBondList));
      list.map((item) => {
        if (item.id == id) {
          item.isAttention = !item.isAttention;
        }
      });
      this.setState({
        newBondList: list,
      });
    } else {
      const list = JSON.parse(JSON.stringify(this.state.newMainList));
      list.map((item) => {
        if (item.id == id) {
          item.isAttention = !item.isAttention;
        }
      });
      this.setState({
        newMainList: list,
      });
    }
  };

  //取消btn
  cancelClick = (type) => {
    this.setState({
      visibleMain: false,
      visibleBond: false,
    });
    if (type == 'bond') {
      this.setState({
        newBondList: [...this.state.bondGroupList],
      });
    } else {
      this.setState({
        newMainList: [...this.state.mainGroupList],
      });
    }
  };

  //确定btn
  sureClick = (type) => {
    const groupIdArr = [];
    const { dataObj, newBondList, newMainList } = this.state;
    if (type == 'bond') {
      const list = newBondList.filter((item) => {
        return item.isAttention;
      });
      list.map((item) => {
        groupIdArr.push(item.id);
      });
      this.props.dispatch({
        type: 'bondDeviationDetailM/updateSecurityGroups',
        payload: {
          groupIdArr: groupIdArr,
          tradingCode: dataObj.TRADINGCODE_NOSUFFIX,
          exchangeCode: dataObj.EXCHANGECODE,
          tradingName: dataObj.SECUABBR,
        },
        callback: (res) => {
          message.success(groupIdArr.length != 0 ? '关注成功' : '取消成功');
          this.setState({
            visibleBond: false,
          });
          this.getAttentionTable();
        },
      });
    } else {
      const list = newMainList.filter((item) => {
        return item.isAttention;
      });
      list.map((item) => {
        groupIdArr.push(item.id);
      });
      this.props.dispatch({
        type: 'bondDeviationDetailM/updateCompanyGroups',
        payload: {
          groupIdArr: groupIdArr,
          comcode: dataObj.COMCODE,
          comname: dataObj.ISSUER,
        },
        callback: (res) => {
          message.success(groupIdArr.length != 0 ? '关注成功' : '取消成功');
          this.setState({
            visibleMain: false,
          });
          this.getAttentionTable();
        },
      });
    }
  };

  //关注下拉列表
  showPopover = (type) => {
    let list;
    let visible;
    let starFilled;
    if (type == 'bond') {
      list = this.state.newBondList;
      visible = this.state.visibleBond;
      starFilled = this.state.starBondFilled;
    } else {
      list = this.state.newMainList;
      visible = this.state.visibleMain;
      starFilled = this.state.starMainFilled;
    }
    return (
      <Popover
        overlayClassName={styles.popoverBox}
        placement='bottom'
        onVisibleChange={() => this.attentionBtn(type)}
        visible={visible}
        content={
          <Spin spinning={this.state.isLoading}>
            <div className={styles.confirm_box}>
              <div className={styles.confirm_list}>
                <ul>
                  {list.map((item) => (
                    <li key={item.id}>
                      <a className={item.isAttention ? styles.a_active : ''} onClick={(e) => this.listClick(e, item.id, type)}>
                        <div className={styles.list_item}>
                          <span>{item.title}</span>
                          <CheckOutlined className={styles.list_icon} />
                        </div>
                      </a>
                    </li>
                  ))}
                </ul>
              </div>
              <div className={styles.confirm_btn}>
                <Button onClick={(e) => this.cancelClick(type)}>取消</Button>
                <Button type='primary' onClick={(e) => this.sureClick(type)}>
                  确定
                </Button>
              </div>
            </div>
          </Spin>
        }
        trigger='click'
      >
        <Tooltip title={starFilled ? '已关注，点击可修改关注' : '未关注，点击可添加关注'} mouseEnterDelay={0.5}>
          <a>
            <LegacyIcon type='star' theme={starFilled ? 'filled' : 'outlined'} style={{ color: styleCommom.debtAndProfit.text[2] }} />
          </a>
        </Tooltip>
      </Popover>
    );
  };

  render() {
    const red = styleCommom.debtAndProfit.text[0];
    const green = styleCommom.debtAndProfit.text[1];
    const { exchangeCode } = this.props;
    const { dataObj } = this.state;
    const { loading } = this.props;
    return (
      <Spin spinning={loading.effects['bondDeviationDetailM/queryBasicInfoSnapshot'] == true}>
        <div className={styles.header_ctx}>
          <div className={styles.header_ctx_box}>
            <span style={{ marginRight: '20px' }}>{dataObj.SECUABBR}</span>
            <div className={styles.header_info_box}>
              <span>{dataObj.TRADINGCODE}</span>
              {isZiGuanEvir() ? null : this.showPopover('bond')}
            </div>
            <div className={styles.header_info_box}>
              <span>{dataObj.ISSUER}</span>
              {isZiGuanEvir() || exchangeCode == '390' ? null : this.showPopover('main')}
            </div>
            {dataObj?.isoption == 1 && <span className={styles.header_logo}>含权债</span>}
          </div>
          <Row type='flex' className={styles.info_row}>
            <Col style={{ width: '12%' }}>
              <p className={styles.info_detail}>
                <span>剩余期限</span>
                <span>{dataObj.TAU}</span>
              </p>
            </Col>
            <Col style={{ width: '11%' }}>
              <p className={styles.info_detail}>
                <span>票面利率</span>
                <span>{dataObj.COUPONRATE}</span>
              </p>
            </Col>
            <Col style={{ width: '13%' }}>
              <p className={styles.info_detail}>
                <span>主体评级</span>
                <span
                  style={{
                    color: dataObj.CREDIADJUSTMENT > 0 ? red : dataObj.CREDIADJUSTMENT == 0 || dataObj.CREDIADJUSTMENT == '-' ? styleCommom.debtAndProfit.text[3] : green,
                  }}
                >
                  {dataObj.CREDITRATING || '-'}
                </span>
                <img
                  src={dataObj.CREDIADJUSTMENT > 0 ? upPng : downPng}
                  style={{ display: dataObj.CREDIADJUSTMENT == 0 || dataObj.CREDIADJUSTMENT == '-' ? 'none' : 'inline-block' }}
                ></img>
              </p>
            </Col>

            <Col style={{ width: dataObj.isBlbg && dataObj.isBlbg == 1 ? '18%' : '13%' }}>
              <p className={styles.info_detail}>
                <span>债项评级</span>
                <span
                  style={{
                    color: dataObj.TARINGADJUSTMENT > 0 ? red : dataObj.TARINGADJUSTMENT == 0 || dataObj.TARINGADJUSTMENT == '-' ? styleCommom.debtAndProfit.text[3] : green,
                  }}
                >
                  {dataObj.RATINGCODE || '-'}
                </span>
                {exchangeCode != '390' ? (
                  <img
                    src={dataObj.TARINGADJUSTMENT > 0 ? upPng : downPng}
                    style={{ display: dataObj.TARINGADJUSTMENT == 0 || dataObj.TARINGADJUSTMENT == '-' ? 'inline-block' : 'inline-block' }}
                  ></img>
                ) : null}
                {dataObj.isBlbg && dataObj.isBlbg == 1 ? <span className={styles.daoqi}>彭博</span> : ''}
              </p>
            </Col>
            {/* 交易市场为390时（境外）不显示 */}
            {exchangeCode != '390' ? (
              <>
                <Col style={{ width: dataObj.isBlbg && dataObj.isBlbg == 1 ? '15%' : '20%' }}>
                  <p className={styles.info_detail}>
                    <span>{dataObj.VALUATIONDATE ? `中债(${dataObj.VALUATIONDATE})` : '中债'}</span>
                    <span
                      style={{
                        color: dataObj.EVALUTEDYIELD_TREND > 0 ? red : dataObj.EVALUTEDYIELD_TREND == 0 ? styleCommom.debtAndProfit.text[3] : green,
                      }}
                    >
                      {dataObj.EVALUTEDYIELD || '-'}
                    </span>
                    <img src={dataObj.EVALUTEDYIELD_TREND > 0 ? upPng : downPng} style={{ display: dataObj.EVALUTEDYIELD_TREND == 0 ? 'none' : 'inline-block' }}></img>

                    {dataObj.VALUATIONTYPE ? <span className={styles.daoqi}>{dataObj.VALUATIONTYPE}</span> : null}
                  </p>
                </Col>
                <Col style={{ width: '15%' }}>
                  <p className={styles.info_detail}>
                    <span>{dataObj.VALUATIONDATE ? `上清(${dataObj.VALUATIONDATE})` : '上清'}</span>
                    <span
                      style={{
                        color: dataObj.SQ_EVALUTEDYIELD_TREND > 0 ? red : dataObj.SQ_EVALUTEDYIELD_TREND == 0 ? styleCommom.debtAndProfit.text[3] : green,
                      }}
                    >
                      {dataObj.SQ_EVALUTEDYIELD || '-'}
                    </span>
                    <img src={dataObj.SQ_EVALUTEDYIELD_TREND > 0 ? upPng : downPng} style={{ display: dataObj.SQ_EVALUTEDYIELD_TREND == 0 ? 'none' : 'inline-block' }}></img>
                  </p>
                </Col>
                <Col style={{ width: '15%' }}>
                  <p className={styles.info_detail}>
                    <span>{dataObj.VALUATIONDATE ? `中证(${dataObj.VALUATIONDATE})` : '中证'}</span>

                    <span
                      style={{
                        color: dataObj.ZZ_EVALUTEDYIELD_TREND > 0 ? red : dataObj.ZZ_EVALUTEDYIELD_TREND == 0 ? styleCommom.debtAndProfit.text[3] : green,
                      }}
                    >
                      {dataObj.ZZ_EVALUTEDYIELD || '-'}
                    </span>
                    <img src={dataObj.ZZ_EVALUTEDYIELD_TREND > 0 ? upPng : downPng} style={{ display: dataObj.ZZ_EVALUTEDYIELD_TREND == 0 ? 'none' : 'inline-block' }}></img>
                  </p>
                </Col>
              </>
            ) : null}
          </Row>
        </div>
      </Spin>
    );
  }
}

export default connect(({ bondDeviationDetailM, loading }) => ({
  bondDeviationDetailM,
  loading,
}))(HeaderC);
